package com.tjjingpan.sharedpreferencestest

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.core.content.edit
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        saveButton.setOnClickListener {
//            val editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit()
//            editor.putString("name","Tom")
//            editor.putInt("age",28)
//            editor.putBoolean("married",false)
//            editor.apply()

            //扩展函数调用方法
            getSharedPreferences("data",Context.MODE_PRIVATE).open {
                putString("name","Tom")
                putInt("age",28)
                putBoolean("married",false)
            }

            //使用Goolge的KTX库中自带的edit函数
            getSharedPreferences("data",Context.MODE_PRIVATE).edit{
                putString("name","Tom")
                putInt("age",28)
                putBoolean("married",false)
            }


        }

        restoreButton.setOnClickListener {
            val prefs = getSharedPreferences("data",Context.MODE_PRIVATE)
            val name = prefs.getString("name","")
            val age = prefs.getInt("age",0)
            val married = prefs.getBoolean("marride",false)
            Log.d("MainActivity","name is $name")
            Log.d("MainActivity","age is $age")
            Log.d("MainActivity","married is $married")
        }
    }
}